package ro.tm.cstaicu.cosmote;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.RemoteViews;

public class CosmoteWidgetProvider extends AppWidgetProvider {

	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		final int N = appWidgetIds.length;

		// Perform this loop procedure for each App Widget that belongs to this
		// provider
		for (int i = 0; i < N; i++) {
//			int appWidgetId = appWidgetIds[i];

			context.startService(new Intent(context,
					CosmoteSMSUpdateService.class));

			// Create an Intent to launch the service on click
			// Intent intent1 = new Intent(context,
			// CosmoteSMSUpdateService.class);
			// PendingIntent pendingIntent1 = PendingIntent.getActivity(context,
			// 0, intent1, 0);
			// RemoteViews views = new RemoteViews(context.getPackageName(),
			// R.layout.layout_widget);
			// views.setOnClickPendingIntent(R.id.linearLayout1,
			// pendingIntent1);

			Log.d("SMSUpdateService:", " started");

			// Tell the AppWidgetManager to perform an update on the current app
			// widget
			// appWidgetManager.updateAppWidget(appWidgetId, views);
		}
	}

	public static class CosmoteSMSUpdateService extends Service {
		@Override
		public void onStart(Intent intent, int startId) {
			Log.d("SMSUpdateService:", " started");
			RemoteViews views = new RemoteViews(getApplication().getPackageName(),
					R.layout.layout_widget);
			views.setTextViewText(R.id.textView1, "Waiting for answer...");
			
			AppWidgetManager manager = AppWidgetManager
					.getInstance(getApplicationContext());

			AppWidgetManager appWidgetManager = AppWidgetManager
					.getInstance(getApplicationContext());
			int[] appWidgetIds = appWidgetManager
					.getAppWidgetIds(new ComponentName(this,
							CosmoteWidgetProvider.class));
			for (int widgetID : appWidgetIds) {
				manager.updateAppWidget(widgetID, views);
			}
			SmsManager sms = SmsManager.getDefault();
			sms.sendTextMessage("1515", null, " ", null, null);
		}

		@Override
		public IBinder onBind(Intent arg0) {
			return null;
		}
	}

}
